/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.actions.login;

import com.mapping.Login;
import com.opensymphony.xwork2.ActionSupport;
import com.session.Session;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.SessionAware;

/**
 *
 * @author Ricardo
 */
@Namespace(value = "/")
@Action(value = "Acceso", results = {
    @Result(name = "success", location = "/Login/AccesoL.jsp")})
public class InicioSesion extends ActionSupport implements SessionAware {

    private String user;
    private String pass;
    private Map<String, Object> sesion;

    @Override
    public String execute() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("inventarios");
        EntityManager em = emf.createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        List<Login> log = em.createNamedQuery("Login.findAll").getResultList();    
        System.out.println(log.size());
        Session s = new Session();
        if (log.size() > 0) {
            for (int i = 0; i < log.size(); i++) {
                Login aux = log.get(i);
                if (aux.getUser().equals(user) && aux.getPass().equals(pass)) {
                    s.setStatus(true);
                    s.setEmpleado(aux.getIdempleado());  
                    s.setLogin(aux);
                }
            }
        } else {
            s.setStatus(false);
        }
        
        sesion.put("Sesion", s);

        tx.commit();
        em.close();
        return SUCCESS;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    @Override
    public void setSession(Map<String, Object> map) {
        this.sesion = map;
    }
}
